
// track_silhouette.cpp : main project file.




#include "stdafx.h"


using namespace System;


int main(int argc, char** argv)
{	
	// Figure out mode
	int mode = 0;

	// DEBUG set mode
	//mode = MODE_PLAYBACK_RAW;
	//mode = MODE_PLAYBACK_RAW | MODE_STREAM;
	mode = MODE_CAPTURE | MODE_STREAM; // | MODE_RECORD_RAW;

	// Local variables
	SilhouetteServer server;
	SilhouetteTracker tracker;
	CvVideoWriter* writerRaw;

   	
	// Setup tracker
	if (mode & MODE_PLAYBACK_RAW)
		tracker.UseRawAVIInstead("raw.avi");

	if (mode & MODE_CAPTURE || mode & MODE_PLAYBACK_RAW) {
		tracker.startTracking();
	}

	// Setup recording
	if (mode & MODE_RECORD_TRACKED) {
		CvVideoWriter *writerTracked = cvCreateVideoWriter("tracked.avi", -1, 15, cvSize(RECORD_TRACKED_WIDTH, RECORD_TRACKED_HEIGHT));
	}
	if (mode & MODE_RECORD_RAW) {
		writerRaw = cvCreateVideoWriter("raw.avi", -1, 15, cvSize(RECORD_RAW_WIDTH, RECORD_RAW_HEIGHT));
	}

	// Setup server
	if (mode & MODE_STREAM) {
		server.setup();
	}


	IplImage* imTransfer;
	IplImage* imForeground;

	

	// Wait for client, if stream mode activated
	if (mode & MODE_STREAM) {
		// Wait for connection
		printf("[Main] Waiting for client to connect\n");		
		server.WaitForConnection();	
		printf("[Main] Client connected\n");
	}

	// Allocate space for transfer image
	if (mode & MODE_STREAM) {
		imTransfer = cvCreateImage(cvSize(RECORD_TRACKED_WIDTH, RECORD_TRACKED_HEIGHT),IPL_DEPTH_8U, 1  );
	}

	// Loop: Capture images and transfer
	while(!tracker.Abort()) {
		// Do tracking
		if (mode & MODE_CAPTURE || mode & MODE_PLAYBACK_RAW) {
			tracker.DoTrack();
		}

		// Record raw
		if (mode & MODE_RECORD_RAW) {
			cvWriteFrame(writerRaw, tracker.GetRaw());
		}


		if (mode & MODE_STREAM) {
			// Get foreground and resize it
			imForeground = tracker.GetForeground();
			cvResize(imForeground, imTransfer, CV_INTER_LINEAR);
			//imTansfer->origin = imForeground->origin;
			
			// Transfer image to client (if client has disconnected, wait for new client)
			if(server.TransferImage(imTransfer)){
				printf("[Main] Image captured and transfered\n");
			} else {
				printf("[Main] Waiting for client to connect\n");		
				server.WaitForConnection();	
				printf("[Main] Client connected\n");
			}

			// Check if the client requested recalibration
			if (server.CheckRecalibration()) {
				printf("[Main] Recalibration on client request\n");
				tracker.recalibrateTracking();
			}

		}
		

		
	}
	

	//cvReleaseImage(&imTransfer);

	if (mode & MODE_RECORD_RAW) {
		cvReleaseVideoWriter(&writerRaw);
	}

    return 0;

	
}

